package zdream.pmfield.storage;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

import java.io.InputStream;
import java.nio.file.Path;
import java.util.List;
import java.util.stream.Collectors;

import zdream.pmfield.data.foe.Ability;

/**
 * @author Zdream
 * @date 2023-12-18
 * @since 0.0.1
 */
public class AbilitiesJsonLoader extends JsonLoader {
	public static List<Ability> loadFromPath(Path path) {
		final JsonArray array = fromPath(path).getAsJsonArray();
		return loadFromJsonArray(array);
	}

	public static List<Ability> loadFromInputStream(InputStream stream) {
		final JsonArray array = fromInputStream(stream).getAsJsonArray();
		return loadFromJsonArray(array);
	}

	public static List<Ability> loadFromJsonArray(JsonArray array) {
		return array.asList().stream()
				.map(JsonElement::getAsJsonObject)
				.map(AbilitiesJsonLoader::loadOne)
				.collect(Collectors.toList());
	}

	public static Ability loadOne(JsonObject object) {
		final int id = object.get("id").getAsInt();
		Ability ability = new Ability(id);

		ability.name = object.get("name").getAsString();
		ability.level = object.get("lv").getAsInt();

		// tags
		final JsonArray tagsArray = object.get("tag").getAsJsonArray();
		ability.tags = tagsArray.asList().stream()
				.map(JsonElement::getAsString)
				.toArray(String[]::new);

		// additions
		JsonElement element = object.get("a");
		if (element != null) {
			ability.additions = MovesJsonLoader.parseAdditionalEffects(element);
		}

		return ability;
	}
}
